<?php

namespace app\http\middleware;

use app\model\AdminTenant;
use app\model\AdminUser;
use app\util\ReturnCode;
use app\util\Tools;
use think\facade\Request;

class CheckUser
{

    /**
     *
     * @param \think\facade\Request $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function handle($request, \Closure $next)
    {
        $header = config('apiadmin.CROSS_DOMAIN');
        $userInfo = $request->API_ADMIN_USER_INFO;
        $id = $request->param('id');

        //如果是root用户，随便操作
        if (isset($id) && intval($id)>0 && !Tools::isAdministrator($userInfo['id'], true)) {
            if (Tools::isAdministrator($userInfo['id'])) {
                //如果是系统管理员,限制不能操作其他管理员用户
                $user = AdminUser::get($id);
                if (!Tools::canOp($userInfo['type'], $user['type'])) {
                    $data = ['code' => ReturnCode::AUTH_REFUSE, 'msg' => '越权操作', 'data' => []];
                    return json($data)->header($header);
                }
            } else {
                //如果不是管理员，就限制只能操作其站点下的非站长用户
                $has = AdminUser::get(['id' => $id, 'tid' => $userInfo['tid']]);
                if (!$has) {
                    $data = ['code' => ReturnCode::AUTH_REFUSE, 'msg' => '越权操作', 'data' => []];
                    return json($data)->header($header);
                }
                $model = AdminTenant::get(['uid' => $id]);
                if ($model) {
                    $data = ['code' => ReturnCode::AUTH_REFUSE, 'msg' => '越权操作', 'data' => []];
                    return json($data)->header($header);
                }
            }
        }
        return $next($request);
    }
}
